import React from 'react';
import PropTypes from 'prop-types';
import { Dropdown, Menu, Balloon } from '@teamix/ui';
import { ButtonIcon } from '@alife/devops-ui';
import { navigate } from 'utils/router';
import { PROJECT_WRITE_ROLES } from 'utils/constants.js';
import track from 'utils/track';
import NotBranchDisabledButton from '../content/components/notBranchDisabledButton';
import { access, protectBranchCheck } from 'components/accessContainer/util';
import { ENUM } from 'utils/constants';
import utils from 'utils';
import intl from '../../../../../../../../locale';

const { Tooltip } = Balloon;

export default class AddOrUploadFileMenu extends React.Component {
  static propTypes = {
    size: PropTypes.string,
    // 树路径，在根目录上传时，为''
    treePath: PropTypes.string,
  };

  static defaultProps = {
    size: 'small',
    treePath: '',
  };

  getProjectInfoFromPageInfo = () => {
    const { pathResource, resourceSubject } = this.props.pageInfo || {};
    const isExist = pathResource.isExist === 'true';
    const isEmpty = pathResource.isEmpty === 'true';
    return {
      isEmpty,
      isExist,
      role: pathResource.role,
      pathResource,
      resourceSubject,
      repoSize: Number(pathResource.repoSize),
      repoLimitSize: Number(pathResource.repoLimitSize),
    };
  };

  goNew = () => {
    const { resourceSubject, pathResource } = this.getProjectInfoFromPageInfo();
    const revision = resourceSubject.revision || 'master';
    const { treePath } = this.props;
    if (treePath) {
      navigate(`/${pathResource.fullPath}/new/${utils.revisionEncodeURI(revision)}/${treePath}`);
    } else {
      navigate(`/${pathResource.fullPath}/new/${utils.revisionEncodeURI(revision)}?isMaster=1`);
    }

    this.props.updateSetSelectedType({
      resourceSubject: {
        subject: 'new',
        path: treePath || '',
      },
    });
  };

  render() {
    const { pathResource } = this.getProjectInfoFromPageInfo();
    const { protectedBranch, size, treePath, followTrigger, lastMirrorSyncRecord } = this.props;
    let isMirrorSynchronizing = false;
    if (lastMirrorSyncRecord) {
      isMirrorSynchronizing = utils.isMirrorSynchronizing(lastMirrorSyncRecord.sync_status);
    }
    if (isMirrorSynchronizing) {
      return (
        <span className={treePath ? '' : 'file-icon-margin-left'}>
          <Tooltip
            trigger={<ButtonIcon name="add-line" disabled size={size} />}
            align="t"
            text={intl.get({
              id: 'code-assets.containers.content.addOrUploadFile.TheRepositoryIsBeingSynchronized',
              defaultMessage: '仓库同步中，暂不支持操作，请稍后再试',
            })}
          />
        </span>
      );
    }

    const { role, isArchive } = pathResource;
    const { access_level } = ENUM;
    const allowProtectPush = protectBranchCheck(protectedBranch, role);
    const isDeveloper = role === access_level[30];

    const { revisionType } = window.FORCE.resourceSubject;

    if (isArchive !== 'false') {
      return null;
    }
    return (
      <>
        {access(PROJECT_WRITE_ROLES, role) && allowProtectPush ? (
          <Dropdown
            trigger={
              <NotBranchDisabledButton
                tooltipText={
                  // intl.get({
                  // id: 'code-assets.containers.content.addOrUploadFile.OperationsCanOnlyBePerformed',
                  // defaultMessage: '只有分支下才可以操作',
                  // })
                  '不支持在标签视图下操作，请切换分支视图再试'
                }
                isIcon
                name="add-line"
                size={size}
              />
            }
            triggerType="click"
            align="tr br"
            hasSelectedIcon={false}
            followTrigger={followTrigger}
          >
            <Menu>
              <Menu.Item
                key="new"
                onClick={() => {
                  track({
                    action: 'new_file',
                    page: 'Repo-Files',
                    control: 'viewtree - newfile',
                  });

                  this.goNew();
                }}
              >
                {intl.get({
                  id: 'code-assets.containers.content.addOrUploadFile.CreateAFile',
                  defaultMessage: '新建文件',
                })}
              </Menu.Item>
              <Menu.Item
                key="upload"
                onClick={() => {
                  track({
                    action: 'upload_file',
                    page: 'Repo-Files',
                    control: 'viewtree - uploadfile',
                  });

                  this.props.onUploadDialogOpen && this.props.onUploadDialogOpen(treePath);
                }}
              >
                {intl.get({
                  id: 'code-assets.containers.content.addOrUploadFile.UploadObjects',
                  defaultMessage: '上传文件',
                })}
              </Menu.Item>
            </Menu>
          </Dropdown>
        ) : (
          <React.Fragment>
            {revisionType === 'tag' ? (
              <Tooltip
                trigger={<ButtonIcon name="add-line" disabled size={size} />}
                align="t"
                text={intl.get({
                  id: 'code-assets.containers.content.addOrUploadFile.OperationsCanOnlyBePerformed',
                  defaultMessage: '只有分支下才可以操作',
                })}
              />
            ) : (
              <Tooltip
                trigger={<ButtonIcon name="add-line" disabled size={size} />}
                align="t"
                text={
                  !access(PROJECT_WRITE_ROLES, role) ? (
                    intl.get({
                      id: 'code-assets.containers.content.addOrUploadFile.YouAreNotAuthorizedTo',
                      defaultMessage:
                        '无权限进行新建文件和上传文件的操作，请联系管理员申请对应的权限',
                    })
                  ) : (
                    <React.Fragment>
                      {isDeveloper
                        ? intl.get({
                            id: 'code-assets.containers.content.addOrUploadFile.TheCurrentBranchIsProtected',
                            defaultMessage: '当前为保护分支，无权限直接推送，请联系管理员处理',
                          })
                        : intl.get({
                            id: 'code-assets.containers.content.addOrUploadFile.CurrentlyItIsAProtected',
                            defaultMessage: '当前为保护分支，无权限直接推送，可前往设置处理',
                          })}
                    </React.Fragment>
                  )
                }
              />
            )}
          </React.Fragment>
        )}
      </>
    );
  }
}
